package net.wang.concurrency.test.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SemaphoreExample3 {

    public static final int threadCount = 20;

    //用单元测试会出现问题
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(3); //并发数是3，一次循环只能有3个线程执行
        for (int i = 0; i < threadCount; i++) {
            final int threadNumber = i;

            executorService.execute(() -> {
                try {
                    if (semaphore.tryAcquire(1, 1, TimeUnit.SECONDS)) {  // 尝试获取一个许可，等待时间1秒
                        out(threadNumber);
                        semaphore.release(); //释放3个许可
                    }
                } catch (InterruptedException e) {
                    log.error("exception : {}", e.getMessage());
                }
            });
        }
        log.info("===== finish ======");
        executorService.shutdown(); //关闭线程池
    }


    private static void out(int threadNumber) throws InterruptedException {
        Thread.sleep(10);
        log.info("num = {}", threadNumber);
    }
}
